package jj.rmirm.manager;

import javax.swing.SwingWorker;

import jj.rmirm.gui.ObjListDisplay;
import jj.rmirm.interfaces.LogDisplayObserver;

public class MonitorThread extends SwingWorker<Void, Void>{

	public MonitorThread(LogDisplayObserver log, ObjListDisplay result) {
		this.result = result;	
		this.manager = RMIManager.getManager();
		this.manager.registerObserver(log);
	}
	
	public void setServerParams(String serverAddr, int serverPort) {
		if(serverAddr.equals("-1") || serverPort == -1) {
			this.allowOperation = false;
			this.manager.informObservers(BAD_IP_OR_PORT);
		}
		else {
			this.manager.setServerParams(serverAddr, serverPort);
			this.allowOperation = true;
		}	
	}
	
	public void startLocalRegistry(boolean start) {
		this.startRegistry = start;
	}
	
	public void setStop(boolean stop) {
		this.stop = stop;
	}
	
	@Override
	protected Void doInBackground() throws Exception {
		if(this.allowOperation) {
			
			if (this.startRegistry)
				this.manager.startLocalRegistry();
			
			this.manager.informObservers(MONITOR_RUNNING);
			while (!stop) {	
				String tmp[] = manager.listObjects();
				if(tmp != null)
					result.updateResult(tmp);
				
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					this.manager.informObservers(THREAD_ERROR);
				}
			}
			
			if(manager.isRegistryRunning())
				manager.stopLocalRegistry();
		}
		else {
			this.manager.informObservers(PRESS_STOP);
		}

		return null;
	}

	private RMIManager manager;
	private boolean stop = false;
	private boolean startRegistry = false;
	private boolean allowOperation = false;
	private ObjListDisplay result;
	
	private static final String THREAD_ERROR = "Thread error";
	private static final String MONITOR_RUNNING = "RMI registry monitoring is running";
	private static final String PRESS_STOP = "Press stop button";
	private static final String BAD_IP_OR_PORT = "Registry server address or port are invalid";
}
